package com.uhu.code;

import java.util.ArrayList;
import java.util.List;

/**
 * 54. 螺旋矩阵
 * https://leetcode.cn/problems/spiral-matrix/description/?envType=study-plan-v2&envId=top-100-liked
 */
public class Solution54 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        List<String> index = new ArrayList<>();
        String control = "right";
        int i = 0, j = 0;
        int last = matrix[0][0];
        int m = matrix.length;
        int n = matrix[0].length;
        int count = 0;
        while(true) {
            if(!index.contains("" + i + j)) {
                result.add(matrix[i][j]);
                index.add("" + i + j);
                last = matrix[i][j];
                count = 0;
            }else {
                if(last == matrix[i][j]) {
                    count++;
                }
                if(count >= 4) {
                    break;
                }
            }

            if(control.equals("down") && i < m) {
                i++;
                if(i >= m || index.contains("" + i + j)) {
                    control = "left";
                    i --;
                }
            }
            if(control.equals("right") && j < n) {
                j++;
                if(j >= n || index.contains( "" + i + j)) {
                    control = "down";
                    j --;
                }
            }
            if(control.equals("up") && i < m) {
                i--;
                if(i < 0 || index.contains( "" + i + j)) {
                    control = "right";
                    i ++;
                }
            }
            if(control.equals("left") && j < n) {
                j--;
                if(j < 0 || index.contains( "" + i + j)) {
                    control = "up";
                    j ++;
                }
            }
        }
        return result;
    }
}
